package com.yadang.admin.log;

import com.yadang.admin.entity.LitemallRole;
import com.yadang.admin.service.ILitemallRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 日志aop拦截
 *
 * @author xpy
 * @date 2021/06/19
 */

@Aspect
@Component
public class LogAspect {

    private static final Logger logger= LoggerFactory.getLogger(LogAspect.class);

    private Map<String,Object> map = new ConcurrentHashMap<>();

    @Autowired
    private ILitemallRoleService roleService;

    /**
     * 这里指定使用 @annotation 指定com.fishpro.aoplog.annotation.Log log注解
     * */
    @Pointcut("@annotation(com.yadang.admin.log.Log)")
    public void logPointCut(){}


    /**
     * 指定当前执行方法在logPointCut之前执行
     * */
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取真实的ip地址
        // logger.info("IP : " + IPAddressUtil.getClientIpAddress(request));
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Log log = signature.getMethod().getAnnotation(Log.class);


        map.put("url",request.getRequestURL().toString());
        map.put("method",request.getMethod());
        map.put("CLASS_METHOD",joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        map.put("参数",Arrays.toString(joinPoint.getArgs()));
        map.put("Log value",log.value());
        map.put("Log type",log.type().toString());

    }
    /**
     * 指定在方法之后返回
     * */
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容(返回值太复杂时，打印的是物理存储空间的地址)
        map.put("ret",ret);
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ob = pjp.proceed();// ob 为方法的返回值
        map.put("time",System.currentTimeMillis() - startTime);
        for (Map.Entry<String, Object> m : map.entrySet()) {
            logger.info("{} : {}",m.getKey(),m.getValue());
        }
        return ob;
    }

    @AfterThrowing(pointcut = "logPointCut()",throwing = "ex")
    public void afterThrowing(Throwable ex){
        System.out.println("################################"+ex.getCause().getMessage());
        for (Map.Entry<String, Object> m : map.entrySet()) {
            logger.info("{} : {}",m.getKey(),m.getValue());
        }
        LitemallRole s = new LitemallRole().setId(44244).setName("真3334的吗");
        roleService.save(s);
    }
}
